<template>
  <div>
    <div>SkuForm</div>
    <!-- :model="" -->
    <el-form label-width="100px" >
      <el-form-item label="SPU名称">
        <div>{{  spuInfo.spuName  }}</div>
      </el-form-item>
      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuForm.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input type="number" placeholder="价格(元)" v-model="skuForm.price"></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)">
        <el-input type="number" placeholder="重量(千克)" v-model="skuForm.weight"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input type="textarea" :rows="3" placeholder="规格描述" v-model="skuForm.skuDesc"></el-input>
      </el-form-item>

      <el-form-item label="平台属性">

        <el-form :inline="true">
          <el-form-item 
          class="mt-15"
          :label="attrInfo.attrName" 
             v-for="attrInfo in  attrInfoList">
            <el-select placeholder="请选择" v-model="attrInfo.attrIdValueId">
              <el-option 
              :value="`${attrInfo.id}:${attrValue.id}`" 
              :label="attrValue.valueName"
               v-for="attrValue in attrInfo.attrValueList"
               ></el-option>
            </el-select>
          </el-form-item>
        </el-form>

      </el-form-item>

      <el-form-item label="销售属性">

        <el-form :inline="true">
          <el-form-item 
           :label="spuSaleAttr.saleAttrName"
           v-for="spuSaleAttr in spuSaleAttrList">
            <el-select placeholder="请选择" v-model="spuSaleAttr.attrIdValueId">
              <el-option 
               :value="`${spuSaleAttr.id}:${saleAttrValue.id}`"
               :label="saleAttrValue.saleAttrValueName"
               v-for="saleAttrValue in spuSaleAttr.spuSaleAttrValueList"
               ></el-option>
             
            </el-select>
          </el-form-item>
        </el-form>

      </el-form-item>

      <el-form-item label="图片列表">
        <!-- :data="" -->
        <el-table border :data="spuImageList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column label="图片">
            <template #default="{ row, $index }">
              <img :src="row.imgUrl" style="width:100px;height:100px">
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row, $index }">
              <el-tag v-if="row.isDefault =='1'" type="success">默认</el-tag>
              <el-button v-else type="primary" size="small" @click="setDefault(row)">设为默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSave">保存</el-button>
        <el-button @click="cancelSave">取消</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted , ref} from 'vue';
import { SPUSTATUS } from '../../index.vue';
import skuApi,{ type SkuModel } from "@/api/sku";
import attrApi,{type AttrModel} from "@/api/attr";
import spuApi ,{type SpuModel ,type SpuImageModel ,type SpuSaleAttrListModel} from "@/api/spu";
import { useCategoryStore }  from "@/stores/category";
import { ElMessage } from 'element-plus';
const categoryStore=useCategoryStore();
const props=defineProps<{
  spuInfo: SpuModel
}>()
const emits = defineEmits(['update:modelValue', 'spuInfo'])

const cancelSave = () => {
  emits('update:modelValue', SPUSTATUS.SPULIST);
  emits('spuInfo')
}

//初始化数据
const initSkuForm = () => {
  return {
    spuId: undefined,
    price: undefined,
    skuName: '',
    skuDesc: '',
    weight: '',
    tmId: undefined,
    category3Id: undefined,
    skuDefaultImg: '', // 默认图片
    createTime: '',
    // 图片列表
    skuImageList: [],
    // 平台属性
    skuAttrValueList: [],
    // 销售属性
    skuSaleAttrValueList: []
  }
}
const skuForm=ref<SkuModel>(initSkuForm());

onMounted(() => {
  initData();
})


//三个接口接收数据且展示
//1-获取平台属性
const attrInfoList=ref<AttrModel[]>()
const getAttrInfoList=async()=>{
  try{
    const  { category1Id, category2Id, category3Id }  =categoryStore;
    let result = await attrApi.getAttrInfoList ( category1Id !, category2Id !, category3Id !);
    // console.log(result)
    attrInfoList.value=result;
    ElMessage.success("获取平台属性成功")
  }catch(err){
    console.log("获取平台属性失败",err);
    ElMessage.error('获取平台属性失败,请重试')
  }
}
//2-获取图片列表
const spuImageList=ref<SpuImageModel[]>()
const getSpuImageList=async()=>{
  try{
    let result=await spuApi.getSpuImageList(props.spuInfo.id as number);
    // console.log(result)
    spuImageList.value=result;
    // console.log(spuImageList.value);
    ElMessage.success("获取图片列表成功")
  }catch(err){
    console.log(err);
    ElMessage.error("获取图片列表失败")

  }
}
 //将图片设置成默认
 const setDefault=(row:SpuImageModel)=>{
  // console.log(row);
  spuImageList.value?.forEach(item=>{
    item.isDefault='0'
  });
  row.isDefault='1'
 }
 //收集选择的图片数据
 const handleSelectionChange = (val:SpuImageModel[]) => {
  // console.log(val)
  skuForm.value.skuImageList = val;
}

//3-获取销售属性
const spuSaleAttrList=ref<SpuSaleAttrListModel>()
const getSaleAttrList=async()=>{
  try{
    let result=await spuApi.getSpuSaleAttrList(props.spuInfo.id as number);
    spuSaleAttrList.value=result;
    ElMessage.success("获取销售属性列表成功")

  }catch(err){
    console.log(err);
    ElMessage.error("获取销售属性列表失败")
  }
}
const initData=()=>{
  getAttrInfoList();
  getSpuImageList();
  getSaleAttrList();
}

//点击保存 提交获取到的数据 请求接口
const onSave=async()=>{
  //默认图片收集
  skuForm.value.skuDefaultImg=spuImageList.value?.find(item=>item.isDefault=='1')?.imgUrl!;
  
  
    //组装平台属性的数据
  // attrInfoList.value=> attrIdValueId: "106:175"
  skuForm.value.skuAttrValueList=attrInfoList.value?.filter(v=>v.attrIdValueId).map(item=>{
      const [attrId,valueId] = (item.attrIdValueId as string).split(':')
      return {
        attrId,
        valueId
      }
  })!
  
  //组装销售属性的数据
 skuForm.value.skuSaleAttrValueList=spuSaleAttrList.value?.filter(v=>v.attrIdValueId).map(item=>{
    const [saleAttrId,saleAttrValueId] =(item.attrIdValueId as string).split(':');
    return {
      saleAttrId,
      saleAttrValueId
    }
 })!

 //组装其他数据
 skuForm.value.spuId=props.spuInfo.id;
 skuForm.value.tmId=props.spuInfo.tmId;
 skuForm.value.category3Id=categoryStore.category3Id;


 //发送请求
 try{
  let result =await skuApi.save(skuForm.value);
  // console.log(result);
  ElMessage.success("保存成功");
  cancelSave();
 }catch(err){
  console.log(err)
  ElMessage.error("保存失败")
 }

}


</script>

<style scoped>
  ::v-deep(.el-form-item__label){
    font-weight: 900;
  }
</style>